#include "chat_room.h"


int main(int argc, char const *argv[])
{
    if(argc != 3){
        printf("User:%s<ip><port>\n",argv[0]);
        exit(-1);
    }

    int sockfd = -1;
    struct sockaddr_in servaddr;
    struct sockaddr_in clientaddr;
    socklen_t addrlen = sizeof(servaddr);

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
        ERRLOG("sockfd error");
    }

    memset(&servaddr,0,addrlen);
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_port = htons(atoi(argv[2]));
    
    if(bind(sockfd, (struct sockaddr*)&servaddr, addrlen) == -1){
        ERRLOG("bind error");
    }

    pid_t pid;
    if((pid = fork()) == -1){
        ERRLOG("fork error");
    }else if(pid > 0){
            MSG msg;
            msg.code = 2;
            strcpy(msg.name, "server");

            while(1){
                fgets(msg.text, sizeof(msg.text), stdin);
                msg.text[strlen(msg.text)-1] = '\0';

                if(sendto(sockfd, &msg,sizeof(msg), 0, (struct sockaddr*)&servaddr, addrlen) == -1){
                    ERRLOG("sendto error");
                }
            }
    }else{
        MSG msg;
        linklist* h = Createlinklist();

        while(1){
            if(recvfrom(sockfd,&msg,sizeof(msg),0,(struct sockaddr*)&clientaddr,&addrlen)==-1){
                printf("errno=%d\n",errno);
                ERRLOG("recvfrom error");
            }

            switch(msg.code){
                case 1://登录操作
                            udpChatLogin(sockfd,msg,h,clientaddr);
                            break;
                case 2://群聊操作
                            udpBroadCast(sockfd,msg,h,clientaddr);
                            break;
                case 3://退出操作
                            udpChatQuit(sockfd,msg,h,clientaddr);
                            break;
                case 4://私聊操作
                            udpChatPrivate(sockfd,msg,h);
                            break;
            }
        }
    }
    return 0;
}
